const router = require("koa-router")();
const rpn = require("request-promise-native");
const { StringDecoder } = require("string_decoder");
const cheerio = require("cheerio");
// const puppeteer = require('puppeteer');
var nodejieba = require("@node-rs/jieba");
var PDFParser = require("pdf2json");
const fs = require("fs");

router.prefix("/jc");

// 获取book目录
router.get("/catalogue", async (ctx, next) => {
  const headers = {
    Accept:
      "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    // 'Accept-Encoding': 'gzip, deflate, br',
    "Accept-Language": "zh-CN,zh;q=0.9",
    Connection: "keep-alive",
    Cookie:
      "pgv_pvid=3778943792; pac_uid=0_57a4897ee956e; shareUuid=836ef6eede414cd6a947b36b10a6f00e; ETCI=5699d32b5da74181b73e3271613c5306; Hm_lvt_6d2e509fb289d49684b88034406cc747=1670980583; ldhbRecord=-1; fuid=ee650bc00e69471db577dd9ac0f16bf2; prefer=; Hm_lpvt_6d2e509fb289d49684b88034406cc747=1670983586",
    Host: "ubook.reader.qq.com",
    "If-None-Match": "32c96-2oqV7bcbLxpeH2cdORodrEkKzcU",
    Referer: "https://ubook.reader.qq.com/publish",
    "sec-ch-ua":
      '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    "sec-ch-ua-mobile": "?1",
    "sec-ch-ua-platform": "Android",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-User": "?1",
    "Upgrade-Insecure-Requests": 1,
    "User-Agent":
      "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36",
  };
  const options = {
    method: "GET",
    uri:
      "https://ubook.reader.qq.com/book-chapter/" + ctx.request.query.id,
    headers: headers,
  };
  const rpnbody = await rpn(options);
  const $ = cheerio.load(rpnbody);
  const recommend_list = $(".catalogueItem");
  const recommend_list_li = [];
  const catalogue = [];
  recommend_list.each((idx, el) => {
    $(el)
      .children()
      .each((idx, el1) => {
        recommend_list_li.push($(el1));
      });
  });
  recommend_list_li.forEach((ele) => {
    catalogue.push(ele.parent()["0"].attribs.title);
  });
  ctx.body = {
    code: 200,
    catalogue,
  };
});
// 获取qq阅读页面
router.get("/qqreader", async (ctx, next) => {
  const headers = {
    Accept:
      "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    // 'Accept-Encoding': 'gzip, deflate, br',
    "Accept-Language": "zh-CN,zh;q=0.9",
    Connection: "keep-alive",
    Cookie:
      "pgv_pvid=3778943792; pac_uid=0_57a4897ee956e; shareUuid=836ef6eede414cd6a947b36b10a6f00e; ETCI=5699d32b5da74181b73e3271613c5306; Hm_lvt_6d2e509fb289d49684b88034406cc747=1670980583; ldhbRecord=-1; fuid=ee650bc00e69471db577dd9ac0f16bf2; prefer=; Hm_lpvt_6d2e509fb289d49684b88034406cc747=1670983586",
    Host: "ubook.reader.qq.com",
    "If-None-Match": "32c96-2oqV7bcbLxpeH2cdORodrEkKzcU",
    Referer: "https://ubook.reader.qq.com/publish",
    "sec-ch-ua":
      '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    "sec-ch-ua-mobile": "?1",
    "sec-ch-ua-platform": "Android",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-User": "?1",
    "Upgrade-Insecure-Requests": 1,
    "User-Agent":
      "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36",
  };
  const options = {
    method: "GET",
    uri: "https://ubook.reader.qq.com/",
    headers: headers,
  };
  const rpnbody = await rpn(options);
  const $ = cheerio.load(rpnbody);
  const newobj = $(".van-swipe-item");
  const carousel = [];
  const hot = [];
  newobj.each(function (idx, el) {
    carousel.push({
      src: $(el).children()[0].children[0].attribs.src,
      href: $(el).children()[0].attribs.href.split("/book-detail/")[1],
    });
  });
  const recommend_list = $(".recommend-list-wrap");
  const recommend_list_li = [];
  recommend_list.each((idx, el) => {
    $(el)
      .children()
      .each((idx, el1) => {
        recommend_list_li.push($(el1));
      });
  });
  recommend_list_li.forEach((ele) => {
    hot.push({
      href: ele.children()[0].attribs.href.split("/book-detail/")[1],
      src: ele.children()[0].children[0].attribs.src,
      alt: ele.children()[0].children[0].attribs.alt,
      title:
        ele.children()[0].children[ele.children()[0].children.length - 1]
          .children[0].children[0].children[0].data,
      score:
        ele.children()[0].children[ele.children()[0].children.length - 1]
          .children[0].children[2].children[0].data,
      intro:
        ele.children()[0].children[ele.children()[0].children.length - 1]
          .children[2].children[0].data,
    });
  });
  ctx.body = {
    code: 200,
    hot,
    carousel,
  };
});
// 获取知乎数据
router.get("/zhihu", async (ctx, next) => {
  const headers = {
    accept:
      "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "max-age=0",
    cookie:
      "_zap=0a762dba-a8d3-436c-9855-061bb16e748e; d_c0=AHAWGa4afhWPTm7xZzAbPR2ejr-WvLBIQGI=|1662019963; _9755xjdesxxd_=32; YD00517437729195%3AWM_TID=hjRiJ7NjADdBFEAFQFLBTPrAQ6BNe3x3; __snaker__id=yJTGHsh99rgJNw2c; YD00517437729195%3AWM_NI=UX2TUEPdeWKIgGvlc7mzx4Vbx1WmrUljTprFIrzBgY0WjriyBPA3%2F1UE8OYPs3YitNMtJiGQY77oKCkVjsC4LMO4XkeKEpe8D6%2B7w%2BdXtGFuXA490%2Ba6%2FNUikt9JCzxCaW8%3D; YD00517437729195%3AWM_NIKE=9ca17ae2e6ffcda170e2e6ee99d06ea9bca8abfb698aef8ab2d14b969a8bb0c45296f5a5ccc65c9bee9eadcb2af0fea7c3b92a9788feb5d84f94bcabb8ca43a599ba8de23dafa6b8d5d56abcef998ef15fb0b69c91f14e8baeb6a3e653f489a693ec7382908fd4ae3b979bf8b0dc5cb1ed978af7468fac868ac65b9be9f990ca49a98aa694c240909381d5db61a7958b91e83488eae5d8f621a888bca8c57f9c9ffcdab321a3eae1afd863a9acf7abc272bc9dafb8bb37e2a3; _xsrf=bf1a4682-90f5-4da8-8269-f5ebf4df3cfc; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1670226401; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1670299018; captcha_session_v2=2|1:0|10:1670299020|18:captcha_session_v2|88:eTBJYTlmWWVUZDM4UGxUN1BXSk5OSE1aa1NGMlZIMXd4T2RKY1VDL2ZPR3ova3dIVXFQRTg0UmxkeWhtUUFIYQ==|97fd0d41be1a892fd74b513b0a6f58e02ea72621510e3a4cfc5d2c252cb54cdd; KLBRSID=37f2e85292ebb2c2ef70f1d8e39c2b34|1670807402|1670807210",
    "sec-ch-ua":
      '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "macOS",
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "none",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": 1,
    "user-agent":
      " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
  };
  const options = {
    method: "GET",
    uri: ctx.request.query.url,
    headers: headers,
  };
  const rpnbody = await rpn(options);
  const $ = cheerio.load(rpnbody);
  $.html();
  ctx.body = $("p").parent().html();
});
// 根据条件查询书目
router.get("/querybook", async (ctx, next) => {
  const headers = {
    accept:
      "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "max-age=0",
    cookie:
      "_zap=0a762dba-a8d3-436c-9855-061bb16e748e; d_c0=AHAWGa4afhWPTm7xZzAbPR2ejr-WvLBIQGI=|1662019963; _9755xjdesxxd_=32; YD00517437729195%3AWM_TID=hjRiJ7NjADdBFEAFQFLBTPrAQ6BNe3x3; __snaker__id=yJTGHsh99rgJNw2c; YD00517437729195%3AWM_NI=UX2TUEPdeWKIgGvlc7mzx4Vbx1WmrUljTprFIrzBgY0WjriyBPA3%2F1UE8OYPs3YitNMtJiGQY77oKCkVjsC4LMO4XkeKEpe8D6%2B7w%2BdXtGFuXA490%2Ba6%2FNUikt9JCzxCaW8%3D; YD00517437729195%3AWM_NIKE=9ca17ae2e6ffcda170e2e6ee99d06ea9bca8abfb698aef8ab2d14b969a8bb0c45296f5a5ccc65c9bee9eadcb2af0fea7c3b92a9788feb5d84f94bcabb8ca43a599ba8de23dafa6b8d5d56abcef998ef15fb0b69c91f14e8baeb6a3e653f489a693ec7382908fd4ae3b979bf8b0dc5cb1ed978af7468fac868ac65b9be9f990ca49a98aa694c240909381d5db61a7958b91e83488eae5d8f621a888bca8c57f9c9ffcdab321a3eae1afd863a9acf7abc272bc9dafb8bb37e2a3; _xsrf=bf1a4682-90f5-4da8-8269-f5ebf4df3cfc; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1670226401; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1670299018; captcha_session_v2=2|1:0|10:1670299020|18:captcha_session_v2|88:eTBJYTlmWWVUZDM4UGxUN1BXSk5OSE1aa1NGMlZIMXd4T2RKY1VDL2ZPR3ova3dIVXFQRTg0UmxkeWhtUUFIYQ==|97fd0d41be1a892fd74b513b0a6f58e02ea72621510e3a4cfc5d2c252cb54cdd; KLBRSID=37f2e85292ebb2c2ef70f1d8e39c2b34|1670807402|1670807210",
    "sec-ch-ua":
      '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "macOS",
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "none",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": 1,
    "user-agent":
      " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
  };
  const options = {
    method: "GET",
    uri:
      "https://ubook.reader.qq.com/api/search?keywords=" +
      encodeURI(ctx.request.query.keywords) +
      "&pageIndex=" +
      ctx.request.query.pageIndex +
      "&pageSize=20&bookType=1&categoryid=0&sorted=" +
      ctx.request.query.bookType,
    headers: headers,
  };
  const rpnbody = await rpn(options);
  ctx.body = rpnbody;
});
// 查询章节
router.get("/querysection", async (ctx, next) => {
  const headers = {
    Accept: "application/json, text/plain, */*",
    "Accept-Language": "zh-CN,zh;q=0.9",
    Connection: "keep-alive",
    Cookie:
      "pgv_pvid=3778943792; pac_uid=0_57a4897ee956e; shareUuid=836ef6eede414cd6a947b36b10a6f00e; ETCI=5699d32b5da74181b73e3271613c5306; Hm_lvt_6d2e509fb289d49684b88034406cc747=1670980583; ldhbRecord=-1; fuid=ee650bc00e69471db577dd9ac0f16bf2; prefer=; testCk=1; Hm_lpvt_6d2e509fb289d49684b88034406cc747=1671010475",
    Host: "ubook.reader.qq.com",
    Referer:
      "https://ubook.reader.qq.com/api/book/read?bid=" +
      ctx.request.query.id +
      "&cid=" +
      (ctx.request.query.cid - 1),
    "sec-ch-ua":
      '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
    "sec-ch-ua-mobile": "?1",
    "sec-ch-ua-platform": "Android",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "User-Agent":
      "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36",
  };
  const options = {
    method: "GET",
    uri:
      "https://ubook.reader.qq.com/api/book/read?bid=" +
      ctx.request.query.id +
      "&cid=" +
      ctx.request.query.cid,
    headers: headers,
  };
  const rpnbody = await rpn(options);
  ctx.body = rpnbody;
});
// 获取基金公司列表
router.get("/lsjz", async (ctx, next) => {
  const headers = {
    Host: "api.fund.eastmoney.com",
    "User-Agent":
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:100.0) Gecko/20100101 Firefox/100.0",
    Accept: "*/*",
    "Accept-Language":
      "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
    "Accept-Encoding": "gzip, deflate",
    Referer: "http://fundf10.eastmoney.com/",
    Connection: "keep-alive",
    Cookie:
      "HAList=a-sz-002129-%u4E2D%u73AF%u80A1%u4EFD%2Ca-sz-300755-%u534E%u81F4%u9152%u884C%2Ca-sz-002869-%u91D1%u6EA2%u79D1%u6280; em_hq_fls=js; qgqp_b_id=b68c421bde94f0da5f00c948a8c40476; st_si=11746531144002; st_sn=47; st_psi=20220519144219464-112200305282-9800314171; st_asi=delete; Eastmoney_Fund=110022_004685; EMFUND0=null; EMFUND1=null; EMFUND2=null; EMFUND3=05-17%2017%3A04%3A23@%23%24%u6613%u65B9%u8FBE%u6D88%u8D39%u884C%u4E1A%u80A1%u7968@%23%24110022; EMFUND4=05-17%2017%3A13%3A36@%23%24%u65B9%u6B63%u8BC1%u5238%u91D1%u7ACB%u65B9%u4E00%u5E74%u6301%u6709%u671F%u6DF7%u5408A@%23%24970009; EMFUND5=05-17%2017%3A43%3A35@%23%24%u4E1C%u65B9%u81FB%u4EAB%u7EAF%u503A%u503A%u5238A@%23%24003837; EMFUND6=05-17%2017%3A44%3A23@%23%24%u5149%u5927%u9633%u5149%u6DFB%u5229%u503A%u5238A@%23%24860005; EMFUND7=05-17%2023%3A47%3A34@%23%24%u4EA4%u94F6%u79D1%u6280%u521B%u65B0%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408C@%23%24015394; EMFUND8=05-19%2009%3A21%3A48@%23%24%u4EBA%u4FDD%u884C%u4E1A%u8F6E%u52A8%u6DF7%u5408A@%23%24006573; EMFUND9=05-19 14:42:22@#$%u4EBA%u4FDD%u8D27%u5E01A@%23%24004903; st_pvi=56634482923323; st_sp=2021-05-28%2015%3A43%3A00; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink",
    "Upgrade-Insecure-Requests": 1,
    Pragma: "no-cache",
    "Cache-Control": "no-cache",
  };
  const options = {
    method: "GET",
    uri:
      "http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery18305891642406583896_1652939541874&fundCode=" +
      ctx.request.query.fundCode +
      "&pageIndex=" +
      ctx.request.query.pageIndex +
      "&pageSize=" +
      ctx.request.query.pageSize +
      "&startDate=&endDate=&_=" +
      Date.now(),
    headers: headers,
  };
  const rpnbody = await rpn(options);
  const data1 = rpnbody.split("(");
  const data2 = eval(
    "(" + data1[1].split(")")[0].replace(new RegExp('\\\\"', "gm"), '"') + ")"
  );
  ctx.body = {
    code: 200,
    data: data2,
  };
});
// 获取blob记录，根据
router.post("/getJClist", async (ctx, next) => {
  const options = {
    method: "POST",
    uri: "http://www.cninfo.com.cn/new/hisAnnouncement/query",
    form: ctx.request.body,
  };
  const rpnbody = await rpn(options);
  ctx.body = {
    code: 200,
    data: rpnbody,
  };
});
// 获取基金公司列表
router.get("/FundSearchAPISearch", async (ctx, next) => {
  const options = {
    method: "GET",
    uri:
      "http://fundsuggest.eastmoney.com/FundSearch/api/FundSearchAPI.ashx?callback=jQuery18308048168429634_1652923505132&m=1&key=" +
      ctx.request.query.key +
      "&_=" +
      Date.now(),
  };
  const rpnbody = await rpn(options);
  const data1 = rpnbody.split('"Datas":');
  const data2 = eval(
    "(" + data1[1].split("})")[0].replace(new RegExp('\\\\"', "gm"), '"') + ")"
  );
  ctx.body = {
    code: 200,
    data: data2,
  };
});
// 获取基金公司列表
router.get("/FundSearchAPI", async (ctx, next) => {
  const options = {
    method: "GET",
    uri:
      "http://fundsuggest.eastmoney.com/FundSearch/api/FundSearchAPI.ashx?callback=jQuery18308048168429634_1652923505132&m=3&key=" +
      ctx.request.query.key +
      "&_=" +
      Date.now(),
  };
  const rpnbody = await rpn(options);
  const data1 = rpnbody.split('"Datas":');
  const data2 = eval(
    "(" + data1[1].split("})")[0].replace(new RegExp('\\\\"', "gm"), '"') + ")"
  );
  ctx.body = {
    code: 200,
    data: data2,
  };
});
// 获取blob记录，根据
router.post("/getJClist", async (ctx, next) => {
  const options = {
    method: "POST",
    uri: "http://www.cninfo.com.cn/new/hisAnnouncement/query",
    form: ctx.request.body,
  };
  const rpnbody = await rpn(options);
  ctx.body = {
    code: 200,
    data: rpnbody,
  };
});

router.post("/getDataList", async (ctx, next) => {
  let pda = await rpn({
    method: "Get",
    uri: ctx.request.body,
    resolveWithFullResponse: true,
    Headers: {
      "Access- Control - Expose - Headers": "Content - Disposition",
    },
    encoding: null,
    json: false, // 这个看你的参数而定
  });
  let filename =
    ctx.request.body.split("/")[ctx.request.body.split("/").length - 1];
  const ret = await new Promise(function (resolve, reject) {
    fs.writeFile(filename, pda.body, function (err) {
      if (err) {
        ctx.body = {
          code: 200,
          data: [],
        };
      } else {
        resolve();
      }
    });
  });
  let pdf = new PDFParser(this, 1);
  pdf.loadPDF("./" + filename);
  const datalist = await new Promise(function (resolve, reject) {
    pdf.on("pdfParser_dataReady", (pdfData) => {
      let str = pdf
        .getRawTextContent()
        .replaceAll(" ", "")
        .replaceAll("\r", "")
        .replaceAll("\n", "")
        .replaceAll("。", "")
        .replaceAll("、", "")
        .replaceAll("了", "")
        .replaceAll("，", "")
        .replaceAll(",", "")
        .replaceAll("：", "")
        .replaceAll("-", "")
        .replaceAll(".", "")
        .replaceAll("（", "")
        .replaceAll("）", "")
        .replaceAll("【", "")
        .replaceAll("】", "")
        .replaceAll("%", "")
        .replaceAll("(", "")
        .replaceAll(")", "");
      for (let i = 0; i < 10; i++) {
        str = str.replaceAll(i + "", "");
        str = str.replaceAll(i, "");
      }
      str = str.replaceAll("□", "");
      str = str.replaceAll("”", "");
      str = str.replaceAll("@", "");
      str = str.replaceAll("一", "");
      str = str.replaceAll(" ", "");
      str = str.replaceAll("的", "");
      const result = nodejieba.cut(str);
      const newmap = {};
      for (let i = 0; i < result.length; i++) {
        if (newmap[result[i]]) {
        } else {
          for (let j = i + 1; j < result.length; j++) {
            if (result[i] == result[j]) {
              if (newmap[result[j]]) {
                newmap[result[j]] = newmap[result[j]] + 1;
              } else {
                newmap[result[j]] = 1;
              }
            }
          }
        }
      }
      const newmaplist = [];
      for (const key in newmap) {
        let option = {};
        option.value = newmap[key];
        option.name = key;
        newmaplist.push(option);
      }
      let swap = {};
      for (let k = 0; k < newmaplist.length; k++) {
        for (var i = 0; i < newmaplist.length; i++) {
          for (var j = i; j < newmaplist.length - 1; j++) {
            if (newmaplist[j].value < newmaplist[j + 1].value) {
              swap = newmaplist[j];
              newmaplist[j] = newmaplist[j + 1];
              newmaplist[j + 1] = swap;
            }
          }
        }
      }
      resolve(newmaplist);
    });
  });
  if (datalist.length < 10) {
    ctx.body = {
      code: 200,
      data: [],
    };
  } else {
    ctx.body = {
      code: 200,
      data: datalist,
    };
  }
});

module.exports = router;
